/**
 * @Description :
 *
 * @Return : 员工
 * @Author : zhangke
 * @Date : 2020/6/20 9:33
 */

$(function () {
    page_emp_department_tree();
    page_emp_tree_dialog();
    page_emp_grid_main();
})

/**
 * 树编辑
 */
function page_emp_tree_dialog() {
    $('#page_emp_tree_dialog').dialog({
        width: 270,
        height: 260,
        resizable: true,
        modal: true,
        closed: true,
        title: '新增',
        iconCls: 'icon-edit',
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                let title = $('#page_emp_tree_dialog').dialog('options').title;
                let formData = new FormData($('#page_emp_tree_dialog_form')[0]);
                if (title == '修改') {
                    let selected = $('#page_emp_department_tree').tree('getSelected');
                    formData.append('id', selected.id);
                }
                if ($('#page_emp_tree_dialog_form').form('validate'))
                    $.ajax({
                        url: (function () {
                            if (title == '修改')
                                return 'department/updateSelective';
                            else
                                return 'department/insertSelective';
                        })(),
                        data: formData,
                        type: 'POST',
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (data) {
                            if (data.success) {
                                $('#page_emp_tree_dialog').dialog('close');
                                $('#page_emp_department_tree').tree('reload');
                            }
                            $.messager.show({title: '提示', msg: data.message});
                        },
                        error: function () {

                        }
                    })
            }
        }, {
            text: '取消',
            iconCls: 'icon-no',
            handler: function () {
                $('#page_emp_tree_dialog').dialog('close');
            }
        }],
        onClose: function () {
            $('#page_emp_tree_dialog_form').form('clear');
        },
    })
}

function page_emp_grid_main() {
    let menuId = 2;
    let SUFFIX = '';
    let id = new kendo.data.DataSource([]);
    let emp_name = new kendo.data.DataSource([]);
    let emp_serial_no = new kendo.data.DataSource([]);
    let emp_number = new kendo.data.DataSource([]);
    let department_name = new kendo.data.DataSource([]);
    let emp_sex = new kendo.data.DataSource([]);
    let duty = new kendo.data.DataSource([]);
    let identity_card = new kendo.data.DataSource([]);
    let birth_place = new kendo.data.DataSource([]);
    let marry_state = new kendo.data.DataSource([]);
    let nation = new kendo.data.DataSource([]);
    let telephone_no_01 = new kendo.data.DataSource([]);
    let telephone_no_02 = new kendo.data.DataSource([]);
    let endowment_insurance = new kendo.data.DataSource([]);
    let housing_provident_fund = new kendo.data.DataSource([]);
    let identity_card_address = new kendo.data.DataSource([]);
    let current_address = new kendo.data.DataSource([]);
    let emp_state = new kendo.data.DataSource([]);
    let other_01 = new kendo.data.DataSource([]);
    let other_02 = new kendo.data.DataSource([]);
    let other_03 = new kendo.data.DataSource([]);
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "employee/report",
                dataType: "json",
                type: "GET",
                data: {
                    departmentId: (function () {
                        let selected = $('#page_emp_department_tree').tree('getSelected');
                        if (selected) {
                            if (selected.id == 1) return null;
                            return selected.id;
                        } else {
                            return null;
                        }
                    })()
                }
            }
        },
        schema: {
            model: {
                fields: {
                    entry_date: {type: 'date'},
                    leave_date: {type: 'date'},
                    create_time: {type: "date"},
                    extra_file_count: {type: 'number'},
                }
            }
        },
        aggregate: [
            {field: "extra_file_count", aggregate: "sum"},
        ],
        pageSize: 500,
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            id.data(unique(data, 'id'));
            emp_name.data(unique(data, 'emp_name'));
            emp_serial_no.data(unique(data, 'emp_serial_no'));
            emp_state.data(unique(data, 'emp_state'));
            emp_number.data(unique(data, 'emp_number'));
            department_name.data(unique(data, 'department_name'));
            emp_sex.data(unique(data, 'emp_sex'));
            duty.data(unique(data, 'duty'));
            identity_card.data(unique(data, 'identity_card'));
            birth_place.data(unique(data, 'birth_place'));
            marry_state.data(unique(data, 'marry_state'));
            nation.data(unique(data, 'nation'));
            telephone_no_01.data(unique(data, 'telephone_no_01'));
            telephone_no_02.data(unique(data, 'telephone_no_02'));
            endowment_insurance.data(unique(data, 'endowment_insurance'));
            housing_provident_fund.data(unique(data, 'housing_provident_fund'));
            identity_card_address.data(unique(data, 'identity_card_address'));
            current_address.data(unique(data, 'current_address'));
            other_01.data(unique(data, 'other_01'));
            other_02.data(unique(data, 'other_02'));
            other_03.data(unique(data, 'other_03'));
        },
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    })

    let columns = [
        {field: '', title: "序号", template: "<span class='row-number'></span>", width: 50},
        {
            field: 'id',
            title: '编号',
            width: 98,
            footerTemplate: '总计:',
            filterable: {multi: true, search: true, checkAll: true, dataSource: id},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'emp_name',
            title: '姓名',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: emp_name},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'emp_serial_no',
            title: '文档系统编号',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: emp_serial_no},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'emp_number',
            title: '工号',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: emp_number},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'department_name',
            title: '部门名',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: department_name},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'emp_sex',
            title: '性别',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: emp_sex},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'emp_state',
            title: '员工状态',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: emp_state},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'duty',
            title: '职务',
            width: 98,
            filterable: {multi: true, search: true, checkAll: true, dataSource: duty},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'}
        },
        {
            field: 'entry_date',
            title: '入职日期',
            width: 98,
            format: "{0: yyyy-MM-dd}",
            headerAttributes: {style: 'text-align:center;'},
            attributes: {class: 'kendo-custum-char'}
        },
        {
            field: 'create_time',
            title: '建档日期',
            width: 98,
            format: "{0: yyyy-MM-dd HH:mm:ss}",
            headerAttributes: {style: 'text-align:center;'},
            attributes: {class: 'kendo-custum-char'}
        },
        {
            field: 'leave_date',
            title: '离职日期',
            width: 98,
            format: "{0: yyyy-MM-dd}",
            headerAttributes: {style: 'text-align:center;'},
            attributes: {class: 'kendo-custum-char'}
        },
        {
            field: 'telephone_no_01',
            title: '电话号码01',
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            filterable: {multi: true, search: true, checkAll: true, dataSource: telephone_no_01},
        },
        {
            field: 'telephone_no_02',
            title: '电话号码02',
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            filterable: {multi: true, search: true, checkAll: true, dataSource: telephone_no_02},
        },
        {
            field: 'endowment_insurance',
            title: '养老保险号码',
            width: 110,
            filterable: {multi: true, search: true, checkAll: true, dataSource: endowment_insurance},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'housing_provident_fund',
            title: '公积金号码',
            width: 70,
            filterable: {multi: true, search: true, checkAll: true, dataSource: housing_provident_fund},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "identity_card_address",
            title: '身份证住址',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: identity_card_address},
            attributes: {class: 'kendo-custum-char'},
            footerAttributes: {style: "text-align:right;"},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "identity_card",
            title: '身份证号码',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: identity_card},
            attributes: {class: 'kendo-custum-char'},
            footerAttributes: {style: "text-align:right;"},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'current_address',
            title: '现住址',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: current_address},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'nation',
            title: '民族',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: nation},
            format: "{0:n1}",
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'other_01',
            title: '其他1',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: other_01},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'other_02',
            title: '其他2',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: other_02},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'other_03',
            title: '其他3',
            width: 92,
            filterable: {multi: true, search: true, checkAll: true, dataSource: other_03},
            attributes: {class: 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'extra_file_count',
            width: 110,
            title: '附件数量',
            template: function (item) {
                return item.extra_file_count ? parseFloat(item.extra_file_count).toFixed(0) : ''
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            format: "{0:n1}",
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: "text-align:right;"}
        },
    ];
    let grid = $("#page_emp_grid_main").kendoGrid({
        sortable: true,
        resizable: true,
        allowCopy: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        title: "报表",
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        excel: {
            fileName: "员工档案.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        columnMenu: {
            sortable: true
        },
        height: '99%',
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row-number");
                $(rowLabel).html(index);
            });
        },
        columnResize: function (e) {
            let field = e.column.field;
            let newWidth = e.newWidth;
            let oldWidth = e.oldWidth;
            if (newWidth < 20) {
                $(this).hideColumn(field);
            } else {
                $.post("userDeploy/update/single", {
                    menuId: menuId,
                    field: field + SUFFIX,
                    width: newWidth
                }, function (data) {
                    if (data.success) {
                    }
                }, "json");
            }
        },
        columnHide: function (e) {  //列隐藏事件
            let field = e.column.field;
            $.post("userDeploy/update/single", {menuId: menuId, field: field + SUFFIX, hidden: true}, function (data) {
            }, "json");
        },
        columnShow: function (e) {  //列显示事件
            let field = e.column.field;
            $.post("userDeploy/update/single", {menuId: menuId, field: field + SUFFIX, hidden: false}, function (data) {
            }, "json");
        },
        columnReorder: function (e) {
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex)
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNo: i,
                        menuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'userDeploy/update/batch',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    //  绑定双击事件
    grid.on('dblclick', 'tr', function (e) {
        let kGrid = $('#page_emp_grid_main').data('kendoGrid');
        let selectItem = kGrid.dataItem(e.currentTarget);
        if (selectItem) {
            $('#page_emp_editable_dialog').dialog('open');
            $.ajax({
                url: 'employee/queryByPk/' + selectItem.id,
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    if (data) {
                        $('#page_emp_editor_form').form('load', data);
                        $.disableFormElement($('#page_emp_editor_form'));
                        $('#page_emp_editor_file_grid').edatagrid('disableEditing');
                        $('#page_emp_editor_file_grid').datagrid('loadData', {
                            total: data.detail.length,
                            rows: data.detail
                        });
                    }
                }
            })
        }
    })
    let k = $('#page_emp_grid_main').data('kendoGrid');
    let columnNames = [];
    columns.forEach(item => {
        let arr = {};
        if (item['field']) {
            arr.field = item['field'] + SUFFIX;
            arr.hidden = item['hidden'] ? true : false;
            arr.width = item['width'] ? item['width'] : null;
            arr.menuId = menuId;
            columnNames.push(arr);
        }
    })
    loadOptions(k, columnNames, columns, SUFFIX);
}

function page_emp_department_tree() {
    $('#page_emp_department_tree').tree({
        url: 'department/tree',
        queryParams: {parentId: null},
        method: 'GET',
        onLoadSuccess: function (node, data) {
            if (data != undefined && data.length > 0) {
                let node = $(this).tree('find', data[0].id);
                $(this).tree('select', node.target);
            }
        },
        onSelect: function (node) {
            let kGrid = $('#page_emp_grid_main').data('kendoGrid');
            if (kGrid != undefined) {
                kGrid.dataSource.read({
                    departmentId: node.id == 1 ? null : node.id
                })
            }
        }
    })
}

function btn_page_emp_add() {
    let selected = $('#page_emp_department_tree').tree('getSelected');
    if ($('#page_emp_department_tree').tree('getParent', selected.target) == undefined) {
        $.messager.alert('提示', '无法在根节点新增', 'warning')
        return;
    }
    $('#page_emp_editable_dialog').dialog('setTitle', '新增编辑');
    $('#page_emp_editable_dialog').dialog('open');
    $.enableFormElement($('#page_emp_editor_form'));
    $('#page_emp_editor_file_grid').edatagrid('enableEditing');
    if (selected) {
        $('#page_emp_editor_form').form('load', {
            departmentId: selected.id
        })
        let loadData = $('#emp_empState').combobox('getData');
        if (loadData) {
            for (let i of loadData) {
                if (i.text == selected.text) {
                    $('#emp_empState').combobox('setValue', i.text);
                    return;
                }
            }
        }
    }
}

function btn_page_emp_update() {
    $('#page_emp_editable_dialog').dialog('open');
    $('#page_emp_editable_dialog').dialog('setTitle', '修改编辑');
    $.enableFormElement($('#page_emp_editor_form'));
    $('#page_emp_editor_file_grid').edatagrid('enableEditing');
    let kGrid = $('#page_emp_grid_main').data('kendoGrid');
    let selectItem = kGrid.dataItem(kGrid.select());
    if (selectItem) {
        $('#page_emp_editable_dialog').dialog('open');
        $.ajax({
            url: 'employee/queryByPk/' + selectItem.id,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                if (data) {
                    $('#page_emp_editor_form').form('load', data);
                    $('#page_emp_editor_file_grid').datagrid('loadData', {
                        total: data.detail.length,
                        rows: data.detail
                    });
                }
            }
        })
    }
}

/** 菜单按钮 **/
function btn_page_emp_delete() {
    let k = $('#page_emp_grid_main').data('kendoGrid');
    let dataItem = k.dataItem(k.select());
    if (dataItem)
        $.messager.confirm('提示', '是否删除？删除后可在回收站找回', function (r) {
            if (r) {
                $.ajax({
                    url: 'employee/updateSelective',
                    type: 'POST',
                    data: {id: dataItem.id, docStatus: 0},
                    success: function (data) {
                        if (data.success) {
                            k.dataSource.read({});
                        }
                        $.messager.show({title: data.state, msg: data.message});
                    }
                })
            }
        })
}

// 导出Excel
function btn_page_emp_export() {
    let k = $('#page_emp_grid_main').data('kendoGrid');
    if (k != undefined)
        k.saveAsExcel();
}

// 导入
function btn_page_emp_import() {
    $('#page_emp_import_dialog').dialog('open');
}

// 网格重置
function btn_page_emp_reload() {
    let kGrid = $('#page_emp_grid_main').data('kendoGrid');
    if (kGrid == undefined) return;
    $.get('userDeploy/reset', {menuId: 2}, function (data) {
    }, 'json');
}

function btn_page_emp_no() {

}

/** 菜单按钮 **/

/** Tree按钮 **/
function btn_page_emp_tree_add() {
    $('#page_emp_tree_dialog').dialog({
        title: '新增'
    })
    let selected = $('#page_emp_department_tree').tree('getSelected');
    if (selected) {
        $('#page_emp_tree_dialog_form').form('load', {
            departmentParentId: (function () {
                let parent = $('#page_emp_department_tree').tree('getParent', selected.target);
                return parent ? parent.id : selected.id;
            })(),
            detartmentStatus: 1
        });
    }
    $('#page_emp_tree_dialog').dialog('open');
}

function btn_page_emp_tree_update() {
    let selected = $('#page_emp_department_tree').tree('getSelected');
    if (!selected) {
        $.messager.alert('提示', '未选中节点!', 'warning');
        return;
    }
    $('#page_emp_tree_dialog').dialog({
        title: '修改'
    })
    $.get('department/queryByPk/' + selected.id, {}, function (data) {
        if (data) {
            $('#page_emp_tree_dialog_form').form('load', data);
        }
    }, 'json')
    $('#page_emp_tree_dialog').dialog('open');
}

function btn_page_emp_tree_delete() {
    let selected = $('#page_emp_department_tree').tree('getSelected');
    if (!selected) {
        $.messager.alert('提示', '未选中节点!', 'warning');
        return;
    }
    $.messager.confirm('提示', '是否删除该节点', function (r) {
        if (r) {
            $.post('department/updateSelective', {id: selected.id, detartmentStatus: 0}, function (data) {
                if (data && data.success) {
                    $('#page_emp_department_tree').tree('reload');
                }
                $.messager.show({title: data.state, msg: data.message});
            }, 'json');
        }
    })
}

/** 导入 */
function btn_page_emp_import_dialog_exporttemp() {
    // 导出Excel模板
    window.open("employee/download/template?token=" + getTokenFromStorage(), "_blank");
}

function btn_page_emp_import_dialog_import() {
    $.messager.confirm('提示', '确定导入?', function (r) {
        if (r) {
            $.ajax({
                url: 'employee/upload/fromExcel',
                type: 'POST',
                data: new FormData($('#page_emp_import_form')[0]),
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (data) {
                    if (data.success) {
                        $('#page_emp_import_dialog').dialog('close');
                    }
                    $.messager.show({title: data.state, msg: data.message})
                }
            })
        }
    })
}
